package com.xiaoyg.algorithm;

public class KthToLast {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        node4.next=node5;

        System.out.println(kthToLast(node1,3));

    }


    static class ListNode{
        int val;
        ListNode next;

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }

        public ListNode(int val){
            this.val = val;
        }
        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }

    }

    public static int kthToLast(ListNode head, int k){
        ListNode slow = head;
        ListNode fast = head;
        //快指针先行k步
        for (int i = 0;i< k;i++){
            fast = fast.next;
        }
        //快指针走到尾部
        while (fast!=null){
            fast = fast.next;
            slow = slow.next;
        }
        //慢指针的位置刚好是倒数第k个节点
        return slow==null?0:slow.val;
    }

}

